import { reqGetcode,reqUserRegister, reqUserLogin, reqGetUserinfo, reqlogout} from '@/api/request'

const state = {
    usercode:'',
    token:localStorage.getItem('token'),
    userinfo:{},
}
const mutations = {
    GETCODE(state,code){
        state.usercode = code
    },
    USERLOGIN(state,token){
        state.token = token
    },
    GETUSERINFO(state,userinfo){
        state.userinfo = userinfo
    },
    // 清除本地数据
    CLEAR(state){
        state.userinfo = {}
        state.token = ''
        localStorage.removeItem('token')
    }
}
const actions = {
    // 获取注册验证码
    async getcode({commit},phone){
        let result = await reqGetcode(phone)
        if(result.code===200){
            commit('GETCODE',result.data)
        }else{
            return Promise.reject(new Error('获取验证码失败'))
        }
    },
    // 注册用户接口
    async UserRegister({commit},user){
        console.log(user);
        let result = await reqUserRegister(user)
        console.log(result);
        if(result.code===200){
            return '注册成功'
        }else{
            return Promise.reject(new Error(result.message))
        }
    },
    // 用户登录接口 存储服务器返回的token值
    async userLogin({commit}, data){
        let result = await reqUserLogin(data);
        if(result.code===200){
            localStorage.setItem('token',result.data.token)
            commit('USERLOGIN',result.data.token)
            return '登录成功'
        }else{
            return Promise.reject(new Error('登录失败'))
        }
    },
    // 获取用户详细信息
    async getuserInfo({commit}){
        let result = await reqGetUserinfo()
        if(result.code===200){
            commit('GETUSERINFO',result.data)
        }
        else{
            return Promise.reject(new Error('faile'))
        }
    },
    // 退出登录
    async userlogout({commit}){
        let result = await reqlogout();
        if(result.code===200){
            // 清除state中的userinfo和token数据
            commit('CLEAR')
        }else{
            return Promise.reject(new Error('退出登录失败'))
        }
    }

}
const getters = {
    code(state){
        return state.usercode
    }
}
export default{
    state,
    mutations,
    actions,
    getters
}